﻿using System;
using System.ComponentModel;
using System.ServiceModel;
using System.Windows;
using StreamingClient.Localization;
using StreamingClient.Player;
using StreamingClient.StreamService;

namespace StreamingClient.StreamManagment
{
    //[Obsolete("Not Supported at the moment", true)]
    public class WmvAccess : IServerAccess
    {
        public void Seek(double pos)
        {
            
        }

        public void UpdatePos(Action<double> callback)
        {
            
        }

        public event EventHandler<StreamingEventArgs> StreamingStarted;
        public event EventHandler<ErrorEventArgs> CommunicationFailed;

        private StreamingSettings _settings;

        private StreamServiceClient _streamService;
        BackgroundWorker bw;
        bool bwquit = false;
        private bool _isCanceling;


        public WmvAccess(StreamingSettings settings)
        {
            _settings = settings;
        }

        public void StartStreaming(string source)
        {
            
            _streamService = new StreamServiceClient("StreamService.IStreamService",
                                            "http://" + _settings.Host + ":" +
                                            _settings.ControlPort + "/StreamService/");
            _streamService.StartStreamCompleted += new EventHandler<StartStreamCompletedEventArgs>(svc_StartStreamCompleted);
            
                IStreamService svc = (IStreamService) _streamService;
                svc.BeginStartStream2(source, _settings.StreamPort, (int) _settings.VFps, _settings.VWidth,
                                      _settings.VHeight, _settings.VBitrate, _settings.ABitrate, _settings.ASampleRate,
                                      _settings.AChannels, v2cb, source);



        }

        private void v2cb(IAsyncResult ar)
        {
            IStreamService svc = _streamService;
            var source = (string) ar.AsyncState;
            try
            {
                var ret=svc.EndStartStream2(ar);
                svc_StartStreamCompleted(_streamService, new StartStreamCompletedEventArgs(new object[]{ret}, null, false, null));
            }
            catch (ActionNotSupportedException)
            {
                _streamService.StartStreamAsync(source, _settings.StreamPort);
            }
            catch (Exception ex)
            {
                svc_StartStreamCompleted(_streamService, new StartStreamCompletedEventArgs(null, ex, true, null));
            }
        }



        void svc_StartStreamCompleted(object sender, StreamService.StartStreamCompletedEventArgs e)
        {
            if (_isCanceling) return;

            if (e.Error != null)
            {
                if (e.Error is EndpointNotFoundException)
                {
                    if (CommunicationFailed != null)
                    {
                        CommunicationFailed(this, new ErrorEventArgs(ErrorCode.ServerMissing,null));
                    }
                }
                else
                {
                    if (CommunicationFailed != null)
                    {
                        CommunicationFailed(this, new ErrorEventArgs(ErrorCode.StartStream, e.Error));
                    }
                }

                return;
            }
            bwquit = false;
            bw = new BackgroundWorker();
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerAsync();

            var uri = new Uri("http://" + _settings.Host + ":" + _settings.StreamPort + "/1.wmv");

            if (StreamingStarted != null)
            {
                //var target = string.Format("http://{0}:{1}/{2}.wmv", _settings.Host, _settings.Port, "stream");
                StreamingStarted(this, new StreamingEventArgs(uri.ToString()));
            }
        }

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            int i = 0;
            System.Threading.Thread.Sleep(30000);
            while (!bwquit)
            {
                i++;
                _streamService.HeartBeatAsync();
                //if (i == 2 && App.IsTrial)
                {
                    //Dispatcher.BeginInvoke(() => { NavigationService.Navigate(new Uri("/BuyPage.xaml", UriKind.Relative)); });
                    
                }
                System.Threading.Thread.Sleep(30000);
            }
        }


        public void StopStreaming()
        {
            _isCanceling = true;

            if (_streamService != null)
            {
                _streamService.StopStreamCompleted += new EventHandler<AsyncCompletedEventArgs>(svc_StopStreamCompleted);
                _streamService.StopStreamAsync(_streamService);
                _streamService = null;
            }
            bwquit = true;
        }

        void svc_StopStreamCompleted(object sender, AsyncCompletedEventArgs e)
        {
            ((StreamServiceClient)e.UserState).Abort();
        }
    }
}
